package com.ala4.oxcafe.mybatis;

import com.ala4.oxcafe.boot.manager.CustomUserDetails;
import com.ala4.oxcafe.boot.utils.DetailsHelper;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * mybatis-plus自动填充
 *
 * @author PING
 * @version 1.0
 * @date 2025/3/6 14:12
 */
@Slf4j
@Component
public class MybatisPlusMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        log.debug("开始插入填充...");

        this.strictInsertFill(metaObject, "createTime", LocalDateTime::now, LocalDateTime.class);
        this.strictInsertFill(metaObject, "updateTime", LocalDateTime::now, LocalDateTime.class);
        this.strictInsertFill(metaObject, "version", () -> 1L, Long.class);
        this.strictInsertFill(metaObject, "delFlag", () -> 0, Integer.class);

        CustomUserDetails userDetails = DetailsHelper.getUserDetails();

        if (userDetails != null) {
            this.strictInsertFill(metaObject, "createBy", userDetails::getUserAccount, String.class);
            this.strictInsertFill(metaObject, "updateBy", userDetails::getUserAccount, String.class);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.debug("开始更新填充...");
        this.setFieldValByName("updateTime", LocalDateTime.now(), metaObject);
        CustomUserDetails userDetails = DetailsHelper.getUserDetails();
        if (userDetails != null) {
            this.setFieldValByName("updateBy", userDetails.getUserAccount(), metaObject);
        }
    }
}
